package com.morningstar.system.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.morningstar.common.base.BaseController;
import com.morningstar.common.dao.entity.CommonQuery;
import com.morningstar.common.logger.operate.OperateLog;
import com.morningstar.common.result.Result;
import com.morningstar.common.result.ServiceCheckResult;
import com.morningstar.system.controller.entity.UpdatePassword;
import com.morningstar.system.controller.query.SysUserQuery;
import com.morningstar.system.dao.entity.SysUser;
import com.morningstar.system.service.SysUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.morningstar.common.constants.permission.PermissionConstants.*;

/**
 * 系统用户接口
 *
 * @author yls
 * @since 2023-06-15
 */
@Slf4j
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    private static final String PERMISSION = "system.user";
    private static final String PERMISSION_LIST = PERMISSION + LIST;
    private static final String PERMISSION_DETAIL = PERMISSION + DETAIL;
    private static final String PERMISSION_UPDATE = PERMISSION + UPDATE;
    private static final String PERMISSION_ADD = PERMISSION + ADD;
    private static final String PERMISSION_DELETE = PERMISSION + DELETE;
    private static final String PERMISSION_RESET_PASSWORD = PERMISSION + ".reset.password";

    @Resource
    private SysUserService userService;

    /**
     * 用户列表查询
     *
     * @param commonQuery 查询条件
     * @return 用户列表
     */
    @PostMapping(value = "/list")
    @SaCheckPermission(PERMISSION_LIST)
    public Result<IPage<SysUser>> list(@RequestBody CommonQuery<SysUser, SysUserQuery> commonQuery) {
        return Result.successData(userService.selectPage(commonQuery));
    }

    /**
     * 新增用户
     *
     * @param sysUser 用户
     * @return 基本结果类
     */
    @PostMapping
    @SaCheckPermission(PERMISSION_ADD)
    public Result<Object> add(@RequestBody SysUser sysUser) {
        ServiceCheckResult result = userService.checkAddAndUpdate(sysUser);
        if (result.isResult()) {
            return Result.fail(result.getMessage());
        }
        userService.add(sysUser);
        return Result.successNoData();
    }

    /**
     * 修改用户
     *
     * @param sysUser 用户
     * @return 基本结果类
     */
    @PostMapping("/update")
    @SaCheckPermission(PERMISSION_UPDATE)
    @OperateLog(title = "修改用户")
    public Result<Object> update(@RequestBody SysUser sysUser) {
        ServiceCheckResult result = userService.checkAddAndUpdate(sysUser);
        if (result.isResult()) {
            return Result.fail(result.getMessage());
        }
        userService.update(sysUser);
        return Result.successNoData();
    }

    /**
     * 获取用户详细信息
     *
     * @param userId 用户Id
     * @return 用户详细信息
     */
    @GetMapping("/detail")
    @SaCheckPermission(PERMISSION_DETAIL)
    public Result<SysUser> detail(@RequestParam("userId") Long userId) {
        return Result.successData(userService.detail(userId));
    }

    /**
     * 删除用户
     *
     * @param userId 用户Id
     * @return 基本结果类
     */
    @GetMapping("/delete")
    @SaCheckPermission(PERMISSION_DELETE)
    public Result<Object> delete(@RequestParam("userId") Long userId) {
        ServiceCheckResult result = userService.checkDelete(userId);
        if (result.isResult()) {
            return Result.fail(result.getMessage());
        }
        userService.removeById(userId);
        return Result.successNoData();
    }

    /**
     * 获取登录用户对象
     *
     * @return 登录用户信息
     */
    @GetMapping("/getUserInfo")
    @SaCheckLogin
    public Result<SysUser> loginUserInfo() {
        return Result.successData(userService.loginUserDetail());
    }

    /**
     * 用户下拉选列表
     *
     * @return 用户下拉选列表
     */
    @GetMapping("/select")
    @SaCheckLogin
    public Result<List<SysUser>> select() {
        return Result.successData(userService.list());
    }

    /**
     * 更新用户头像
     *
     * @param avatar 用户头像文件Id
     * @return 基本结果类
     */
    @GetMapping("/updateAvatar")
    @SaCheckLogin
    public Result<Object> updateAvatar(@RequestParam("avatar") String avatar) {
        userService.updateAvatar(avatar);
        return Result.successNoData();
    }

    /**
     * 修改用户信息-登入用户
     *
     * @param sysUser 用户信息
     * @return 基本结果类
     */
    @PostMapping("/updateUserInfo")
    @SaCheckLogin
    public Result<Object> updateUserInfo(@RequestBody SysUser sysUser) {
        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUser::getUserId, StpUtil.getLoginId().toString())
                .set(SysUser::getLoginName, sysUser.getLoginName())
                .set(SysUser::getUserName, sysUser.getUserName())
                .set(SysUser::getEmail, sysUser.getEmail())
                .set(SysUser::getPhone, sysUser.getPhone())
                .set(SysUser::getSex, sysUser.getSex());
        userService.update(updateWrapper);
        return Result.successNoData();
    }

    /**
     * 修改密码-登入用户
     *
     * @param updatePassword 修改密码实体类
     * @return 基本结果类
     */
    @PostMapping("/updatePassword")
    @SaCheckLogin
    public Result<Object> updatePassword(@RequestBody UpdatePassword updatePassword) {
        return userService.updatePassword(updatePassword);
    }

    /**
     * 重置密码-登入用户
     *
     * @param userId 用户Id
     * @return 基本结果类
     */
    @GetMapping("/resetPassword/{userId}")
    @SaCheckPermission(PERMISSION_RESET_PASSWORD)
    public Result<Object> resetPassword(@PathVariable("userId") Long userId) {
        return userService.resetPassword(userId);
    }
}
